package searchteam.beans.entities;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.*;

import searchteam.client.beansMirrors.PaperMirror;
import searchteam.client.beansMirrors.PersonMirror;

@Entity
@Table(name="PERSONS")
public class Person implements Serializable {

	private static final long serialVersionUID = 6248327582024903556L;
	
	private int id;
	private String name;
	private String firstname;
	private String phone;
	private String mail;
	private Team team;
	private Team ownedTeam;
	private Collection<Paper> papers;
	
	private PersonMirror loaded;

	public Person() {
		papers = new ArrayList<Paper>();
	}
	
	public Person(String name, String firstname, String phone, String mail) {
		this.name = name;
		this.firstname = firstname;
		this.phone = phone;
		this.mail = mail;
		papers = new ArrayList<Paper>();
	}

	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getFirstname() {
		return firstname;
	}

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getMail() {
		return mail;
	}

	public void setMail(String mail) {
		this.mail = mail;
	}

	@ManyToMany(mappedBy="authors")
	public Collection<Paper> getPapers() {
		return papers;
	}

	public void setPapers(Collection<Paper> papers) {
		this.papers = papers;
	}

	public void addPaper(Paper paper) {
		papers.add(paper);
	}

	public void removePaper(Paper paper) {
		papers.remove(paper);
	}

	@OneToOne(mappedBy="teamMaster")
	public Team getOwnedTeam() {
		return ownedTeam;
	}

	public void setOwnedTeam(Team team) {
		ownedTeam = team;
	}

	@ManyToOne
	public Team getTeam() {
		return team;
	}

	public void setTeam(Team team) {
		this.team = team;
	}
	
	@Transient
	public PersonMirror getMirror() {
		if(loaded == null) {
			loaded = new PersonMirror();
			loaded.setId(id);
			loaded.setFirstname(firstname);
			loaded.setMail(mail);
			loaded.setName(name);
			loaded.setPhone(phone);
			
			Collection<PaperMirror> paperMirrors = new ArrayList<PaperMirror>();
			for(Paper paper : papers){
				paperMirrors.add(paper.getMirror());
			}
			loaded.setPapers(paperMirrors);

			if(ownedTeam != null) {
				loaded.setOwnedTeam(ownedTeam.getMirror());
			}
			if(team != null) {
				loaded.setTeam(team.getMirror());
			}
		}
		
		return loaded;
	}
	
}
